package com.pwser.atomikos;

import java.sql.SQLException;

import javax.sql.DataSource;

import oracle.jdbc.xa.client.OracleXADataSource;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.jta.atomikos.AtomikosDataSourceBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

//@Configuration
@MapperScan(basePackages = "com.pwser.test1", sqlSessionTemplateRef = "test1SqlSessionTemplate")
public class MyBatisConfig1 {

	// 配置数据源
	@Primary
	@Bean(name = "test1DataSource")
	public DataSource test1DataSource(DBConfig1 test1Config)
			throws SQLException {
		OracleXADataSource oracleXaDataSource = new OracleXADataSource();
		oracleXaDataSource.setURL(test1Config.getUrl());
		oracleXaDataSource.setUser(test1Config.getUsername());
		oracleXaDataSource.setPassword(test1Config.getPassword());
		
		AtomikosDataSourceBean xaDataSource = new AtomikosDataSourceBean();
		xaDataSource.setXaDataSource(oracleXaDataSource);
		xaDataSource.setUniqueResourceName("test1DataSource");

		xaDataSource.setMinPoolSize(test1Config.getMinPoolSize());
		xaDataSource.setMaxPoolSize(test1Config.getMaxPoolSize());
		xaDataSource.setMaxLifetime(test1Config.getMaxLifetime());
		xaDataSource.setBorrowConnectionTimeout(test1Config
				.getBorrowConnectionTimeout());
		xaDataSource.setLoginTimeout(test1Config.getLoginTimeout());
		xaDataSource.setMaintenanceInterval(test1Config
				.getMaintenanceInterval());
		xaDataSource.setMaxIdleTime(test1Config.getMaxIdleTime());
		xaDataSource.setTestQuery(test1Config.getTestQuery());
		return xaDataSource;
	}

	@Primary
	@Bean(name = "test1SqlSessionFactory")
	public SqlSessionFactory test1SqlSessionFactory(
			@Qualifier("test1DataSource") DataSource dataSource)
			throws Exception {
		SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
		bean.setDataSource(dataSource);
		return bean.getObject();
	}

	@Primary
	@Bean(name = "test1SqlSessionTemplate")
	public SqlSessionTemplate test1SqlSessionTemplate(
			@Qualifier("test1SqlSessionFactory") SqlSessionFactory sqlSessionFactory)
			throws Exception {
		return new SqlSessionTemplate(sqlSessionFactory);
	}

}
